package com.ysyc.driver_ee.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.KeyboardView;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysyc.driver_ee.R;
import com.ysyc.driver_ee.api.HttpResource;
import com.ysyc.driver_ee.api.NetworkCallback;
import com.ysyc.driver_ee.api.RetrofitClient;
import com.ysyc.driver_ee.base.BaseActivity;
import com.ysyc.driver_ee.manager.TakePictureManager;
import com.ysyc.driver_ee.model.AuthSubmit;
import com.ysyc.driver_ee.model.FileData;
import com.ysyc.driver_ee.tools.KeyBoardUtils;
import com.ysyc.driver_ee.tools.Keyboard_Util;
import com.ysyc.driver_ee.tools.RegularExpression;
import com.ysyc.driver_ee.tools.ScreenUtils;
import com.ysyc.driver_ee.tools.ToastUtils;
import com.ysyc.driver_ee.widget.TitleView;
import com.ysyc.driver_ee.widget.UploadPhotosPop;

import org.w3c.dom.Text;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * <p>描述：(这里用一句话描述这个类的作用)</p>
 * 作者： Chan<br>
 * 日期： 2018/10/30 15:56<br>
 * 版本： v1.0<br>
 */
public class DriverCertificationActivity extends BaseActivity {


    @BindView(R.id.title_driver_view)
    TitleView titleDriverView;
    @BindView(R.id.et_name_tv)
    EditText etNameTv;
    @BindView(R.id.et_car_number_view)
    EditText etCarNumberView;
    @BindView(R.id.tv_upload_id_card_view)
    TextView tvUploadIdCardView;
    @BindView(R.id.tv_upload_driver_license_view)
    TextView tvUploadDriverLicenseView;
    @BindView(R.id.tv_upload_car_card_view)
    TextView tvUploadCarCardView;
    @BindView(R.id.tv_people_car_view)
    TextView tvPeopleCarView;
    @BindView(R.id.tv_submit_certification_view)
    TextView tvSubmitCertificationView;
    @BindView(R.id.et_area_view)
    EditText etAreaView;
    @BindView(R.id.et_number_view)
    EditText etNumberView;

    @BindView(R.id.keyboard_view)
    KeyboardView keyboardView;
    private Keyboard_Util keyboard_util;
    private UploadPhotosPop uploadPhotosPop;

    private TakePictureManager takePictureManager;

    public AuthSubmit authSubmit = new AuthSubmit();
    private NetworkCallback<Object> objectNetworkCallback;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_driver_certification;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        keyboard_util = new Keyboard_Util(this);
        takePictureManager = new TakePictureManager(this);
        etAreaView.setFocusable(false);
        etAreaView.setOnClickListener(v -> {
            keyboard_util.setEditView(etAreaView, false);
            KeyBoardUtils.hiddenKeyBoard(DriverCertificationActivity.this, etAreaView);
            keyboard_util.showKeyboard();
        });
        etNumberView.setFocusable(false);
        etNumberView.setOnClickListener(v -> {
            etNumberView.setFocusable(true);
            keyboard_util.setEditView(etNumberView, true);

            KeyBoardUtils.hiddenKeyBoard(DriverCertificationActivity.this, etAreaView);
            keyboard_util.showKeyboard();
        });
        initNetworkCallback();
    }

    private void initNetworkCallback() {
        objectNetworkCallback = new NetworkCallback<>(new HttpResource<Object>() {
            @Override
            public void onSuccess(Object o) {
                dismissDilog();
                ToastUtils.show("已上传成功，正在审核中");
            }

            @Override
            public void onFailure(String errorDes) {
                dismissDilog();
                ToastUtils.show(errorDes);
            }

            @Override
            public void onLoading(Dialog dialog) {
                showLoadingDialog();
            }
        });

    }

    private void initTitle() {
        titleDriverView.setTitleViewBackground(R.color.white_ff);
        titleDriverView.setLeftImg(R.drawable.return_icon);
        titleDriverView.setTitle("司机认证",getResources().getColor(R.color.text_black));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int screenHeight = ScreenUtils.getScreenHeight(DriverCertificationActivity.this);
        if (keyboard_util.isShow()) {
            if (ev.getY() < (screenHeight - keyboardView.getHeight())) {
                keyboard_util.hideKeyboard();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (keyboard_util.isShow()) {
                keyboard_util.hideKeyboard();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private void fromAlbum(LinearLayout ll, int type) {
        takePictureManager.startTakeWayByAlbum("亿商用车");
        takePictureManager.setTakePictureCallBackListener(new TakePictureManager.takePictureCallBackListener() {
            @Override
            public void successful(boolean isTailor, String outFilePath, Uri filePath) {
                Bitmap bitmap = BitmapFactory.decodeFile(outFilePath);
                uploadMultiFile(outFilePath, type);
                Drawable drawable = new BitmapDrawable(bitmap);
                ll.setBackground(drawable);
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {

            }
        });
    }

    private void fromCamera(LinearLayout ll, int type) {
        takePictureManager.startTakeWayByCarema("亿商用车");
        takePictureManager.setTakePictureCallBackListener(new TakePictureManager.takePictureCallBackListener() {
            @Override
            public void successful(boolean isTailor, String outFilePath, Uri filePath) {
                Bitmap bitmap = BitmapFactory.decodeFile(outFilePath);
                uploadMultiFile(outFilePath, type);
                Drawable drawable = new BitmapDrawable(bitmap);
                ll.setBackground(drawable);
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        takePictureManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureManager.attachToActivityForResult(requestCode, resultCode, data);
    }

    public void uploadIdCard(View view) {
//        PermissionUtils.requestPermissions(DriverCertificationActivity.this, 1, permisson, mPermissionGrant);
        showPop(view, R.drawable.demonstration_car_id_icon, 2);
    }


    public void uploadDriverLicense(View view) {
//        PermissionUtils.requestPermissions(DriverCertificationActivity.this, 1, permisson, mPermissionGrant);
        showPop(view, R.drawable.driver_license_icon, 1);

    }



    public void uploadCarCard(View view) {
//        PermissionUtils.requestPermissions(DriverCertificationActivity.this, 1, permisson, mPermissionGrant);
        showPop(view, R.drawable.car_card_icon, 3);
    }


    public void peopleCar(View view) {
//        PermissionUtils.requestPermissions(DriverCertificationActivity.this, 1, permisson, mPermissionGrant);
        showPop(view, R.drawable.people_car_icon, 4);
    }

    private void showPop(View view, @DrawableRes int drawableRes, int type) {
        if (null == uploadPhotosPop) {
            uploadPhotosPop = new UploadPhotosPop(DriverCertificationActivity.this);
        }

        uploadPhotosPop.show(view, new UploadPhotosPop.OnPopListener() {
            @Override
            public void onPhotographItemClick(LinearLayout ll) {
                fromCamera(ll, type);
            }

            @Override
            public void onAlbumItemClick(LinearLayout ll) {
                fromAlbum(ll, type);
            }
        }, (LinearLayout) view.getParent());
        uploadPhotosPop.setExampleImageView(drawableRes);
    };

    private void uploadMultiFile(String imgUrl, int type) {
        String url = "http://120.27.22.100:8888/fileServer/fileUpServlet";
        String imageType = "multipart/form-data";
        File file = new File(imgUrl);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "head_image", fileBody)
                .addFormDataPart("imagetype", imageType)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder
                .build();
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                String htmlStr = response.body().string();
                Gson gson = new Gson();
                try {
                    FileData fileData = gson.fromJson(htmlStr, FileData.class);
                    if (1 == type) {
                        authSubmit.authIdcardUrl = fileData.data.filename;
                    } else if (2 == type) {
                        authSubmit.authDriverUrl = fileData.data.filename;
                    } else if (3 == type) {
                        authSubmit.authLicenseUrl = fileData.data.filename;
                    } else if (4 == type) {
                        authSubmit.authCarUnityUrl = fileData.data.filename;
                    }
                } catch (Exception e) {
                    ToastUtils.show("上传失败");
                }


            }
        });
    }

    public void submitCertification(View view) {
        String nameTrim = etNameTv.getText().toString().trim();
        if (TextUtils.isEmpty(nameTrim)) {
            ToastUtils.show("姓名不能为空");
            return;
        }
        authSubmit.name = nameTrim;
        String carNumbertrim = etCarNumberView.getText().toString().trim();
        if (TextUtils.isEmpty(carNumbertrim) && RegularExpression.personIdValidation(carNumbertrim)) {
            ToastUtils.show("请输入正确身份证号信息");
            return;
        }
        authSubmit.idCard = carNumbertrim;
        int i =  37122;
        if (keyboard_util.getprimaryCode()!=0){
            i = keyboard_util.getprimaryCode();
      }



        authSubmit.carForm = i;

        String numberTrim = etNumberView.getText().toString().trim();
        if (!TextUtils.isEmpty(numberTrim)&&numberTrim.length()==6){
            authSubmit.carNumber = numberTrim;
        }else {
            ToastUtils.show("请输入证件信息");
            return;
        }

        if (TextUtils.isEmpty(authSubmit.authIdcardUrl)){
            ToastUtils.show("身份证照片没上传或上传失败，请重新上传");
            return;
        }
        if (TextUtils.isEmpty(authSubmit.authDriverUrl)){
            ToastUtils.show("身份证照片没上传或上传失败，请重新上传");
            return;
        }
        if (TextUtils.isEmpty( authSubmit.authLicenseUrl)){
            ToastUtils.show("身份证照片没上传或上传失败，请重新上传");
            return;
        }
        if (TextUtils.isEmpty(authSubmit.authCarUnityUrl)){
            ToastUtils.show("身份证照片没上传或上传失败，请重新上传");
            return;
        }
        Observable<Object> objectObservable = RetrofitClient.getInstance().getHttpServices().authSubmit(authSubmit);
        objectNetworkCallback.postRequest(objectObservable,null);

    }


}
